﻿using System;
using Sherwood.Content.SearchClient;
using Sherwood.Web;
using SolrNet;

namespace Sherwood.Content.UpdateScheduler
{
    public class SolrRecordSourceProvider : IExistingRecordsSourceProvider
    {
        public SolrRecordSourceProvider(string serviceUrl)
        {
            PageSize = 512;
            SearchProfileName = "Updater";

            SyncRoot = new object();

            SearchClient = new Client(serviceUrl);
            var connection = new SearchConnection(SearchClient);

            Startup.Init<SolrRecord>(connection);
        }

        public Client SearchClient { get; private set; }

        public IExistingRecordsSource GetForClient(string clientId, string privateKey)
        {
            return new SolrRecordSource(this, clientId, privateKey);
        }

        public object SyncRoot { get; private set; }

        public int PageSize { get; set; }

        public string SearchProfileName { get; set; }

        public class Client : ClientSignedSearchClient
        {
            public Client(string searchServiceUrl)
                : base(searchServiceUrl)
            {
                ExtraParameters = new QueryParameterCollection();
            }

            public QueryParameterCollection ExtraParameters { get; private set; }

            public override void PrepareSearchRequest(QueryParameterCollection queryParameters)
            {
                foreach (var parameter in ExtraParameters)
                    queryParameters.Add(parameter);

                base.PrepareSearchRequest(queryParameters);
            }
        }
    }
}